import Foundation

class ServiceDiscovery {
    private var browser: NetServiceBrowser
    private var discoveredServices: [NetService] = []

    init() {
        browser = NetServiceBrowser()
        browser.delegate = self
    }

    func startDiscovery(serviceType: String, domain: String = "local.") {
        browser.searchForServices(ofType: serviceType, inDomain: domain)
    }
}

extension ServiceDiscovery: NetServiceBrowserDelegate {
    func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {
        discoveredServices.append(service)
        print("发现服务: \(service.name)")
        service.delegate = self
        service.resolve(withTimeout: 5.0)
    }

    func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) {
        if let index = discoveredServices.firstIndex(of: service) {
            discoveredServices.remove(at: index)
            print("移除服务: \(service.name)")
        }
    }
}

extension ServiceDiscovery: NetServiceDelegate {
    func netServiceDidResolveAddress(_ sender: NetService) {
        guard let addresses = sender.addresses else { return }
        for address in addresses {
            var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
            if getnameinfo(address, socklen_t(address.withMemoryRebound(to: sockaddr.self, capacity: 1) { $0.pointee }.sa_len), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 {
                let host = String(cString: hostname)
                print("服务地址: \(host)")
            }
        }
    }
}

// 使用示例
let discovery = ServiceDiscovery()
discovery.startDiscovery(serviceType: "_http._tcp.")

RunLoop.current.run()
    